//
//  DHNoticeViewController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/18.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHNoticeViewController.h"
#import "DHNotice_NormalCell.h"
#import "DHNoticeDetail_NOTICE_VC.h"
#import "DHOrderDetail_CheckViewController.h"
#import "DHUserManagerViewController.h"

@interface DHNoticeViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *dataArray;

@property (assign, nonatomic) NSInteger pageIndex;

@end

@implementation DHNoticeViewController

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleLabel.text = @"通知";
    
    UIButton *doneButton = [[UIButton alloc] initWithFrame:CGRectMake(self.navView.width - 74, self.navView.height - 44, 64, 44)];
    [doneButton setTitle:@"全部已读" forState:UIControlStateNormal];
    doneButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [doneButton setTitleColor:[UIColor colorWithHexString:@"#4a4a4a"] forState:UIControlStateNormal];
    [self.navView addSubview:doneButton];
    
    WeakSelf(weakSelf)
    [doneButton bk_addEventHandler:^(id sender) {
        [[DHNetAPIClient shareDHNetAPIClient] request_notifications_readallWithParams:@{} andBlock:^(id data, NSError *error) {
            [weakSelf loadNotice];
        }];
    } forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView.mj_header = [DHMJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNotice)];
    self.tableView.mj_footer = [DHMJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreNotice)];
    [self.tableView.mj_header beginRefreshing];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DHNotice_NormalCell" bundle:nil] forCellReuseIdentifier:kDHNotice_NormalCell];
}

- (void)loadNotice{
    self.pageIndex = 0;
    [[DHNetAPIClient shareDHNetAPIClient] request_user_notificationsWithParams:@{@"pageIndex":@(self.pageIndex),@"pageSize":@(20)} andBlock:^(id data, NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.dataArray removeAllObjects];
        [self.dataArray addObjectsFromArray:[data objectForKey:@"notifications"]];
        if (self.dataArray.count < 20) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        self.pageIndex += 1;
        [self.tableView reloadData];
    }];
}

- (void)loadMoreNotice{
    [[DHNetAPIClient shareDHNetAPIClient] request_user_notificationsWithParams:@{@"pageIndex":@(self.pageIndex),@"pageSize":@(20)} andBlock:^(id data, NSError *error) {
        [self.dataArray addObjectsFromArray:[data objectForKey:@"notifications"]];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource and UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 85;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DHNotice_NormalCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHNotice_NormalCell forIndexPath:indexPath];
    NSDictionary *notice = [self.dataArray objectAtIndex:indexPath.row];
    cell.titleLabel.text = [notice objectForKey:@"title"];
    cell.summaryLabel.text = [notice objectForKey:@"summary"];
    NSDate *date = [NSDate dateWithServerISOString:[notice objectForKey:@"createdAt"] format:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
    cell.timeLabel.text = [NSDate stringFromDate:date withFormat:@"yyyy/MM/dd HH:mm"];
    if ([[notice objectForKey:@"readed"] boolValue]) {
        cell.alphaView.hidden = NO;
    }else{
        cell.alphaView.hidden = YES;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *notice = [[self.dataArray objectAtIndex:indexPath.row] mutableCopy];
    if ([[notice objectForKey:@"category"] isEqualToString:@"ORDER_CLOSED"]) {
        if (![[notice objectForKey:@"readed"] boolValue]) {
            [[DHNetAPIClient shareDHNetAPIClient] request_notifications_readWithParams:@{@"notification_id":[notice objectForKey:@"_id"]} andBlock:^(id data, NSError *error) {
                [notice setObject:@(1) forKey:@"readed"];
                [self.dataArray replaceObjectAtIndex:indexPath.row withObject:notice];
                [tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
            }];
        }
    }else if ([[notice objectForKey:@"category"] isEqualToString:@"NOTICE"]){
        if (![[notice objectForKey:@"readed"] boolValue]) {
            [[DHNetAPIClient shareDHNetAPIClient] request_notifications_readWithParams:@{@"notification_id":[notice objectForKey:@"_id"]} andBlock:^(id data, NSError *error) {
                [notice setObject:@(1) forKey:@"readed"];
                [self.dataArray replaceObjectAtIndex:indexPath.row withObject:notice];
                [tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
                DHNoticeDetail_NOTICE_VC *noticeVC = [[DHNoticeDetail_NOTICE_VC alloc] init];
                noticeVC.htmlString = [notice objectForKey:@"content"];
                [self.navigationController pushViewController:noticeVC animated:YES];
            }];
        }
    }else if ([[notice objectForKey:@"category"] isEqualToString:@"DELIVERED"]){
        if (![[notice objectForKey:@"readed"] boolValue]) {
            [[DHNetAPIClient shareDHNetAPIClient] request_notifications_readWithParams:@{@"notification_id":[notice objectForKey:@"_id"]} andBlock:^(id data, NSError *error) {
                [notice setObject:@(1) forKey:@"readed"];
                [self.dataArray replaceObjectAtIndex:indexPath.row withObject:notice];
                [tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
                DHOrderDetail_CheckViewController *odController = [[DHOrderDetail_CheckViewController alloc] init];
                odController.orderID = [[notice objectForKey:@"data"] objectForKey:@"order_id"];
                [self.navigationController pushViewController:odController animated:YES];
            }];
        }
    }else if ([[notice objectForKey:@"category"] isEqualToString:@"RETURND"]){
        if (![[notice objectForKey:@"readed"] boolValue]) {
            [[DHNetAPIClient shareDHNetAPIClient] request_notifications_readWithParams:@{@"notification_id":[notice objectForKey:@"_id"]} andBlock:^(id data, NSError *error) {
                [notice setObject:@(1) forKey:@"readed"];
                [self.dataArray replaceObjectAtIndex:indexPath.row withObject:notice];
                [tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
            }];
        }
    }else if ([[notice objectForKey:@"category"] isEqualToString:@"BROKEN"]){
        if (![[notice objectForKey:@"readed"] boolValue]) {
            [[DHNetAPIClient shareDHNetAPIClient] request_notifications_readWithParams:@{@"notification_id":[notice objectForKey:@"_id"]} andBlock:^(id data, NSError *error) {
                [notice setObject:@(1) forKey:@"readed"];
                [self.dataArray replaceObjectAtIndex:indexPath.row withObject:notice];
                [tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
                // TODO::
            }];
        }
    }else if ([[notice objectForKey:@"category"] isEqualToString:@"VIP_EXPIRING"]){
        if (![[notice objectForKey:@"readed"] boolValue]) {
            [[DHNetAPIClient shareDHNetAPIClient] request_notifications_readWithParams:@{@"notification_id":[notice objectForKey:@"_id"]} andBlock:^(id data, NSError *error) {
                [notice setObject:@(1) forKey:@"readed"];
                [self.dataArray replaceObjectAtIndex:indexPath.row withObject:notice];
                [tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
                DHUserManagerViewController *umController = [[DHUserManagerViewController alloc] init];
                [self.navigationController pushViewController:umController animated:YES];
            }];
        }
    }
}

@end
